package com.yxw.yxnet_cd_center.customer_service.service.impl;

import com.yxw.yxnet_cd_center.customer_service.entity.YxcscClientFiledServiceEntity;
import com.yxw.yxnet_cd_center.customer_service.entity.YxCsUserEntity;
import com.yxw.yxnet_cd_center.customer_service.entity.YxCsChannelEntity;
import com.yxw.yxnet_cd_center.customer_service.entity.YxCsStandStatisticsEntity;
import com.yxw.yxnet_cd_center.customer_service.entity.YxcscCustomerAccessServiceEntity;
import com.yxw.yxnet_cd_center.customer_service.mapper.StandStatisticsMapper;
import com.yxw.yxnet_cd_center.customer_service.mapper.YxcscClientFiledServiceMapper;
import com.yxw.yxnet_cd_center.customer_service.mapper.UserMapper;
import com.yxw.yxnet_cd_center.customer_service.mapper.FlockMapper;
import com.yxw.yxnet_cd_center.customer_service.mapper.YxcscServiceTalkRecordMapper;
import com.yxw.yxnet_cd_center.customer_service.mapper.YxcscCustomerAccessServiceMapper;
import com.yxw.yxnet_cd_center.customer_service.mapper.ChannelMapper;
import cn.hutool.core.bean.BeanUtil;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yxw.yxnet_cd_center.common.constant.SessionConstants;
import com.yxw.yxnet_cd_center.common.dto.PageVO;
import com.yxw.yxnet_cd_center.common.utils.BaseDateTime;
import com.yxw.yxnet_cd_center.customer_service.dto.ExportStandStatisticsDTO;
import com.yxw.yxnet_cd_center.customer_service.dto.MessageTimeDTO;
import com.yxw.yxnet_cd_center.customer_service.dto.StandStatisticsQueryDTO;
import com.yxw.yxnet_cd_center.customer_service.service.StandStatisticsService;
import com.yxw.yxnet_cd_center.customer_service.utils.PageUtils;
import com.yxw.yxnet_cd_center.customer_service.vo.StandStatisticsVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author fangmaoxin
 * @version 1.0
 * @date 2023年9月22日
 * 客服维护统计-服务类
 */
@Slf4j
@Service
public class StandStatisticsServiceImpl extends ServiceImpl<StandStatisticsMapper, YxCsStandStatisticsEntity> implements StandStatisticsService {

    @Autowired
    private YxcscClientFiledServiceMapper clientFiledServiceMapper;

    @Autowired
    private YxcscCustomerAccessServiceMapper customerAccessServiceMapper;

    @Autowired
    private YxcscServiceTalkRecordMapper serviceTalkRecordMapper;

    @Autowired
    private UserMapper userMapper;

    private static final String DATETIME_FORMATTER = "yyyy-MM-dd HH:mm:ss";

    /**
     * 查询客服维护统计列表
     */
    @Override
    public PageVO<StandStatisticsVo> selectStandStatisticsList(StandStatisticsQueryDTO dto) {
        Page<YxCsStandStatisticsEntity> page = new Page<>(dto.getCurrPage(), dto.getPageSize());
        LambdaQueryWrapper<YxCsStandStatisticsEntity> queryWrapper = getQueryWrapper(dto.getChannelName(), dto.getFlockName(), dto.getCreateTimeStart(), dto.getCreateTimeEnd(), dto.getNickName());

        // 执行查询
        page = baseMapper.selectPage(page, queryWrapper);
        List<YxCsStandStatisticsEntity> entityList = page.getRecords();
        // 使用BeanUtils.copyProperties()将属性复制到StandStatisticsVo列表
        List<StandStatisticsVo> statisticsVoList = new ArrayList<>();
        if (entityList != null && !entityList.isEmpty()) {
            statisticsVoList = BeanUtil.copyToList(entityList, StandStatisticsVo.class);
        }
        return PageUtils.get(page, statisticsVoList);
    }

    private static LambdaQueryWrapper<YxCsStandStatisticsEntity> getQueryWrapper(String dto, String dto1, String dto2, String dto3, String dto4) {
        LambdaQueryWrapper<YxCsStandStatisticsEntity> queryWrapper = new LambdaQueryWrapper<>();
        // 设置查询条件
        if (StringUtils.isNotBlank(dto)) {
            queryWrapper.eq(YxCsStandStatisticsEntity::getChannelName, dto);
        }
        // 设置群名称模糊搜索条件
        if (StringUtils.isNotBlank(dto1)) {
            queryWrapper.like(YxCsStandStatisticsEntity::getFlockName, "%" + dto1 + "%");
        }
        // 客服昵称模糊搜索
        if (StringUtils.isNotBlank(dto4)) {
            queryWrapper.like(YxCsStandStatisticsEntity::getNickName, "%" + dto4 + "%");
        }
        // 设置创建时间筛选条件
        queryWrapper.ge(StringUtils.isNotBlank(dto2), YxCsStandStatisticsEntity::getCreateTime, BaseDateTime.getDate(dto2))
                .le(StringUtils.isNotBlank(dto3), YxCsStandStatisticsEntity::getCreateTime, BaseDateTime.getDate(dto3))
                .orderByDesc(YxCsStandStatisticsEntity::getCreateTime);
        return queryWrapper;
    }


    /**
     * 导出表格
     */
    @Override
    public void exportExcel(HttpServletResponse response, ExportStandStatisticsDTO dto) {

        // 查出数据
        List<YxCsStandStatisticsEntity> list;

        LambdaQueryWrapper<YxCsStandStatisticsEntity> queryWrapper = getQueryWrapper(dto.getChannelName(), dto.getFlockName(), dto.getCreateTimeStart(), dto.getCreateTimeEnd(), dto.getNickName());
        list = baseMapper.selectList(queryWrapper);

        log.info("=======================开始导出文件=========================");
        // 获取当前时间并格式化为数字形式
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String timestamp = now.format(formatter);
        // 导出文件名后添加当前导出的时间
        String fileName = String.format("客服维护统计表%s.xls", timestamp);
        // 调用工具类
        try {
            // 设置响应头
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

            // 创建工作簿
            Workbook workbook = new HSSFWorkbook();
            Sheet sheet = workbook.createSheet("客服维护统计");

            // 写入表头
            String[] headers = {"统计编号", "客服昵称", "渠道名称", "客服名称", "群名称", "历史接待人数", "今日接待人数", "历史满意率",
                    "历史不满意率", "今日满意率", "今日不满意率", "今日三分钟回复率", "历史三分钟回复率", "日平均响应次数", "首次响应人数", "创建时间", "更新时间", "统计日期"};
            Row headerRow = sheet.createRow(0);
            for (int i = 0; i < headers.length; i++) {
                headerRow.createCell(i).setCellValue(headers[i]);
            }
            SimpleDateFormat formatter2 = new SimpleDateFormat(DATETIME_FORMATTER);

            // 写入数据
            int rowIndex = 1;
            for (YxCsStandStatisticsEntity entity : list) {
                Row row = sheet.createRow(rowIndex);
                row.createCell(0).setCellValue(entity.getStatisticsId()); // 统计编号
                row.createCell(1).setCellValue(entity.getNickName());
                row.createCell(2).setCellValue(entity.getChannelName());
                row.createCell(3).setCellValue(entity.getUserName());
                row.createCell(4).setCellValue(entity.getFlockName());
                row.createCell(5).setCellValue(entity.getHisRecepCnt());
                row.createCell(6).setCellValue(entity.getDayRecepCnt());
                row.createCell(7).setCellValue(entity.getHisSatisRate());
                row.createCell(8).setCellValue(entity.getHisNosatisRate());
                row.createCell(9).setCellValue(entity.getDaySatisRate());
                row.createCell(10).setCellValue(entity.getDayNosatisRate());
                row.createCell(11).setCellValue(entity.getDayReplyRate());
                row.createCell(12).setCellValue(entity.getHisReplyRate());
                row.createCell(13).setCellValue(entity.getServiceCnt());
                row.createCell(14).setCellValue(entity.getFirstReplyCnt());
                row.createCell(15).setCellValue(formatter2.format(entity.getCreateTime())); // 创建时间
                row.createCell(16).setCellValue(formatter2.format(entity.getUpdateTime())); // 更新时间
                row.createCell(17).setCellValue(entity.getPDay()); // 统计日期yyyyMMdd
                rowIndex++;
            }
            // 输出到响应流
            try (OutputStream outputStream = response.getOutputStream()) {
                workbook.write(outputStream);
            }
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 通过用户id获取客服维护统计数据
     */
    @Override
    public StandStatisticsVo getStandStatisticsByUserId(Long userId) {
        LocalDate today = LocalDate.now(); // 获取当前日期
        LocalDateTime startOfDay = today.atStartOfDay(); // 今天的开始时间
        LocalDateTime endOfDay = today.atTime(LocalTime.MAX); // 今天的结束时间

        LambdaQueryWrapper<YxCsStandStatisticsEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(YxCsStandStatisticsEntity::getUserId, userId)
                .between(YxCsStandStatisticsEntity::getCreateTime, startOfDay, endOfDay)
                .orderByDesc(YxCsStandStatisticsEntity::getCreateTime);
        List<YxCsStandStatisticsEntity> todayEntities = baseMapper.selectList(lambdaQueryWrapper);

        List<YxCsStandStatisticsEntity> entities = new ArrayList<>();
        if (!todayEntities.isEmpty()) {
            Date latestTime = todayEntities.get(0).getCreateTime();
            for (YxCsStandStatisticsEntity entity : todayEntities) {
                Calendar calendar1 = Calendar.getInstance();
                calendar1.setTime(latestTime);
                Calendar calendar2 = Calendar.getInstance();
                calendar2.setTime(entity.getCreateTime());
                if (calendar1.get(Calendar.HOUR_OF_DAY) == calendar2.get(Calendar.HOUR_OF_DAY) &&
                        calendar1.get(Calendar.MINUTE) == calendar2.get(Calendar.MINUTE)) {
                    entities.add(entity);
                }
            }
        }

        if (!entities.isEmpty()) {
            int totalHisRecepCnt = 0;
            double totalServiceCnt = 0.0;
            double totalDaySatisRate = 0.0;
            double totalDayNosatisRate = 0.0;
            double totalDayReplyRate = 0.0;
            int totalFirstReplyCnt = 0;

            for (YxCsStandStatisticsEntity entity : entities) {
                Integer hisRecepCnt = entity.getHisRecepCnt(); // 历史接待数
                Double serviceCnt = entity.getServiceCnt(); // 日平均响应次数
                String daySatisRateStr = entity.getDaySatisRate(); // 今日满意率
                String dayNosatisRateStr = entity.getDayNosatisRate(); // 今日不满意率
                String dayReplyRateStr = entity.getDayReplyRate(); // 今日三分钟回复率
                Integer firstReplyCnt = entity.getFirstReplyCnt(); // 首次响应人数

                totalHisRecepCnt += hisRecepCnt;
                // 计算serviceCnt百分比数值并累加总和
                totalServiceCnt += serviceCnt;
                // 计算百分比数值并累加总和
                totalDaySatisRate += Double.parseDouble(daySatisRateStr.replace("%", ""));
                totalDayNosatisRate += Double.parseDouble(dayNosatisRateStr.replace("%", ""));
                totalDayReplyRate += Double.parseDouble(dayReplyRateStr.replace("%", ""));
                totalFirstReplyCnt += firstReplyCnt;

            }
            int totalDays = entities.size();
            // 计算平均值
            double avgDaySatisRate = totalDaySatisRate / totalDays;
            double avgDayNosatisRate = totalDayNosatisRate / totalDays;
            double avgDayReplyRate = totalDayReplyRate / totalDays;
            double avgServiceCnt = totalServiceCnt / totalDays;
            double avgFirstReplyCnt = (double) totalFirstReplyCnt / totalDays;

            StandStatisticsVo result = new StandStatisticsVo();
            result.setHisRecepCnt(totalHisRecepCnt);
            result.setServiceCnt(avgServiceCnt);
            // 设置平均值
            result.setDaySatisRate(String.format("%.2f", avgDaySatisRate) + "%");
            result.setDayNosatisRate(String.format("%.2f", avgDayNosatisRate) + "%");
            result.setDayReplyRate(String.format("%.2f", avgDayReplyRate) + "%");
            result.setFirstReplyCnt((int) avgFirstReplyCnt);
            return result;
        } else {
            return null;
        }
    }

    /**
     * 更新客服维护统计数据
     */
    @Override
    @Transactional
    public void insertStandStatistics() {
        // 客户发起会话详情数据
        List<YxcscClientFiledServiceEntity> sessionEntityList = clientFiledServiceMapper.selectList(new LambdaQueryWrapper<>());

        LocalDateTime todayStart = LocalDate.now().atStartOfDay();
        LocalDateTime todayEnd = LocalDateTime.now().with(LocalTime.MAX).plusSeconds(1);
        LocalDate today = LocalDate.now();
        LocalDate yesterday = today.minusDays(1);
        if (sessionEntityList != null && !sessionEntityList.isEmpty()) {
            Map<Long, List<YxcscClientFiledServiceEntity>> channelSessionMap = new HashMap<>(); // 根据客服id对他接待的数据进行分组 key=客服id  value = 他名下客户发起服务的明细数据
            for (YxcscClientFiledServiceEntity sessionEntity : sessionEntityList) {
                List<YxcscClientFiledServiceEntity> channelSessionList = channelSessionMap.getOrDefault(
                        sessionEntity.getCoustId(), new ArrayList<>()
                );
                channelSessionList.add(sessionEntity);
                channelSessionMap.put(sessionEntity.getCoustId(), channelSessionList);
            }
            // 统计每个客服接待的数量
            int todayReceptionCount; // 今日接待人数
            int receptionCount; // 历史接待数
            // 准备一个结果集
            List<YxCsStandStatisticsEntity> statisticsList = new ArrayList<>();
            for (Map.Entry<Long, List<YxcscClientFiledServiceEntity>> entry : channelSessionMap.entrySet()) {
                if (entry.getKey() != null) {
                    Long coustId = entry.getKey();
                    List<YxcscClientFiledServiceEntity> channelSessionList = entry.getValue();

                    // 使用 Java 8 的流操作，根据 createTime 升序排序，取第一个元素
                    OptionalLong earliestCreateTimeOptional = getOptionalLong(channelSessionList);
                    long daysUsed = 0;
                    LocalDate earliestUsageDate = null;
                    if (earliestCreateTimeOptional.isPresent()) {
                        long earliestCreateTime = (earliestCreateTimeOptional.getAsLong()) / 1000; // 最开始使用的时间戳
                        LocalDateTime earliestDateTime = Instant.ofEpochSecond(earliestCreateTime).atZone(ZoneId.systemDefault()).toLocalDateTime(); // 转换为 LocalDateTime
                        earliestUsageDate = earliestDateTime.toLocalDate(); // 转换为日期对象
                        // 获取当天的开始时间和结束时间
                        daysUsed = ChronoUnit.DAYS.between(earliestUsageDate, today);  // 计算天数差
                    }

                    // 计算历史咨询数
                    receptionCount = (int) channelSessionList.stream().filter(s -> coustId.equals(s.getCoustId())).count();
                    // 计算今日接待数量
                    todayReceptionCount = getTodayReceptionCount(channelSessionList, coustId, todayStart, todayEnd);
                    int satisfiedCount = 0; // 满意会话数量
                    int dissatisfiedCount = 0; // 不满意会话数量
                    int todaySatisfiedCount = 0; // 今日满意会话数量
                    int todayDissatisfiedCount = 0; // 今日不满意会话数量
                    int historicalThreeMinuteReplyCount = 0; // 历史三分钟回复数量
                    int todayThreeMinuteReplyCount = 0; // 今日三分钟回复数量
                    int firstResponseCount = 0; // 客服首次响应数量
                    String sessionId = null;

                    YxCsStandStatisticsEntity statistics = new YxCsStandStatisticsEntity();
                    for (YxcscClientFiledServiceEntity sessionEntity : channelSessionList) {
                        statistics.setNickName(sessionEntity.getCoustName());
                        LambdaQueryWrapper<YxCsUserEntity> wrapper = new LambdaQueryWrapper<>();
                        wrapper.eq(YxCsUserEntity::getUserId, sessionEntity.getCoustId());
                        YxCsUserEntity userEntity = userMapper.selectOne(wrapper);
                        if (userEntity != null) {
                            statistics.setUserName(userEntity.getUserName());
                        }
                        statistics.setChannelName(sessionEntity.getChannelName());
                        statistics.setNickName(sessionEntity.getCoustName());
                        statistics.setUserId(sessionEntity.getCoustId());
                        sessionId = sessionEntity.getId();
                        if (sessionEntity.getCoustId().equals(coustId)) {
                            Integer evaluate = sessionEntity.getEvaluate();
                            LocalDateTime createTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(sessionEntity.getCreateTime()), ZoneId.systemDefault());
                            boolean isTodaySession = createTime.isAfter(todayStart) && createTime.isBefore(todayEnd);
                            if (evaluate != null) {
                                satisfiedCount += (evaluate >= SessionConstants.FULLY_SATISFIED) ? 1 : 0;
                                dissatisfiedCount += (evaluate >= SessionConstants.FULLY_SATISFIED) ? 0 : 1;
                                if (isTodaySession) {
                                    todaySatisfiedCount += (evaluate >= SessionConstants.FULLY_SATISFIED) ? 1 : 0;
                                    todayDissatisfiedCount += (evaluate >= SessionConstants.FULLY_SATISFIED) ? 0 : 1;
                                }
                            }
                            if (sessionId != null) {
                                List<MessageTimeDTO> timeDTO = serviceTalkRecordMapper.findTalkRecordCreateTimeBySessionId(sessionId);
                                if (timeDTO != null && !timeDTO.isEmpty()) {
                                    for (MessageTimeDTO messageTimeDTO : timeDTO) {
                                        if (null != messageTimeDTO.getSenderUserTime() && null != messageTimeDTO.getSenderCustomerTime()) {
                                            Long senderCustomerTime = messageTimeDTO.getSenderCustomerTime();
                                            Long senderUserTime = messageTimeDTO.getSenderUserTime();
                                            LocalDateTime customerTime = Instant.ofEpochMilli(senderCustomerTime).atZone(ZoneId.systemDefault()).toLocalDateTime();
                                            LocalDateTime userTime = Instant.ofEpochMilli(senderUserTime).atZone(ZoneId.systemDefault()).toLocalDateTime();

                                            // 计算时间间隔，并比较是否在三分钟内
                                            Duration duration = Duration.between(customerTime, userTime);
                                            long durationSeconds = duration.getSeconds();
                                            if (durationSeconds <= 180) {  // 180秒为三分钟的秒数
                                                historicalThreeMinuteReplyCount++;

                                                // 判断回复时间是否是今天的
                                                LocalDate replyDate = userTime.toLocalDate();
                                                LocalDate customerReplyDate = customerTime.toLocalDate();
                                                if (today.equals(replyDate) || today.equals(customerReplyDate)) {
                                                    todayThreeMinuteReplyCount++;
                                                }
                                                if (earliestUsageDate != null && earliestUsageDate.equals(replyDate)) {
                                                    firstResponseCount++;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    double satisfactionRate = (double) satisfiedCount / receptionCount * 100; // 历史满意率
                    double dissatisfactionRate = (double) dissatisfiedCount / receptionCount * 100; // 历史不满意率
                    double historicalThreeMinuteReplyRate = (double) historicalThreeMinuteReplyCount / receptionCount * 100; // 历史三分钟回复率
                    double todaySatisfactionRate = (todayReceptionCount == 0) ? 0.0 : ((double) todaySatisfiedCount / todayReceptionCount * 100); // 今日满意率
                    double todayDissatisfactionRate = (todayReceptionCount == 0) ? 0.0 : ((double) todayDissatisfiedCount / todayReceptionCount * 100); // 今日不满意率
                    double todayThreeMinuteReplyRate = (todayReceptionCount == 0) ? 0.0 : ((double) todayThreeMinuteReplyCount / todayReceptionCount * 100); // 今日三分钟回复率
                    double averageReplyCountPerDay = daysUsed != 0 ? (double) historicalThreeMinuteReplyCount / daysUsed : 0.0; // 日平均响应次数
                    statistics.setFlockName(getFlockNameByUserId(coustId));
                    statistics.setHisRecepCnt(receptionCount);
                    statistics.setDayRecepCnt(todayReceptionCount);
                    statistics.setHisSatisRate(String.format("%.2f", satisfactionRate) + "%");
                    statistics.setHisNosatisRate(String.format("%.2f", dissatisfactionRate) + "%");
                    setEntity2(statistics, todaySatisfactionRate, todayDissatisfactionRate, todayThreeMinuteReplyRate, historicalThreeMinuteReplyRate, averageReplyCountPerDay, firstResponseCount);
                    statisticsList.add(statistics);
                }
            }
            List<YxCsStandStatisticsEntity> selectedList = baseMapper.selectList(new LambdaQueryWrapper<>());
            if (!selectedList.isEmpty()) {
                // 找出selectedList中创建时间是最新的一条
                YxCsStandStatisticsEntity latestEntity = selectedList.stream()
                        .max(Comparator.comparing(YxCsStandStatisticsEntity::getCreateTime))
                        .orElse(null);

                if (latestEntity != null) {
                    Date createDate = latestEntity.getCreateTime();
                    LocalDateTime creationDateTime = LocalDateTime.ofInstant(createDate.toInstant(), ZoneId.systemDefault());
                    LocalDate creationDate = creationDateTime.toLocalDate();

                    if (creationDate.isEqual(today)) {
                        // 如果创建时间是今天之内，则删除今天的所有数据
                        baseMapper.delete(new LambdaQueryWrapper<YxCsStandStatisticsEntity>()
                                .ge(YxCsStandStatisticsEntity::getCreateTime, todayStart)
                                .le(YxCsStandStatisticsEntity::getCreateTime, todayEnd));
                        super.saveBatch(statisticsList);
                    } else if (creationDate.isEqual(yesterday)){
                        // 如果创建时间是在昨天，则直接执行批量新增
                        super.saveBatch(statisticsList);
                    } else {
                        // 如果创建时间是更早的日期，则根据业务逻辑进行相应处理
                        super.saveBatch(statisticsList);
                    }
                }
            }
        }
    }

    private static void setEntity2(YxCsStandStatisticsEntity statistics, double todaySatisfactionRate, double todayDissatisfactionRate, double todayThreeMinuteReplyRate, double historicalThreeMinuteReplyRate, double averageReplyCountPerDay, int firstResponseCount) {
        statistics.setDaySatisRate(String.format("%.2f", todaySatisfactionRate) + "%");
        statistics.setDayNosatisRate(String.format("%.2f", todayDissatisfactionRate) + "%");
        statistics.setDayReplyRate(String.format("%.2f", todayThreeMinuteReplyRate) + "%");
        statistics.setHisReplyRate(String.format("%.2f", historicalThreeMinuteReplyRate) + "%");
        statistics.setServiceCnt(averageReplyCountPerDay); // 日平均响应次数
        statistics.setFirstReplyCnt(firstResponseCount); // 首次响应次数
        statistics.setCreateTime(new Date());
        statistics.setUpdateTime(new Date());
        // 将时间戳格式化为yyyyMMdd日期格式
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String pDay = dateFormat.format(new Date());
        statistics.setPDay(Integer.valueOf(pDay));
    }

    private static OptionalLong getOptionalLong(List<YxcscClientFiledServiceEntity> channelSessionList) {
        return channelSessionList.stream()
                .mapToLong(YxcscClientFiledServiceEntity::getCreateTime)
                .min();
    }

    private static int getTodayReceptionCount(List<YxcscClientFiledServiceEntity> channelSessionList, Long coustId, LocalDateTime todayStart, LocalDateTime todayEnd) {
        int todayReceptionCount;
        todayReceptionCount = (int) channelSessionList.stream()
                .filter(s -> s.getCoustId().equals(coustId))
                .filter(s -> {
                    LocalDateTime createTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(s.getCreateTime()), ZoneId.systemDefault());
                    return createTime.isAfter(todayStart) && createTime.isBefore(todayEnd);
                }).count();
        return todayReceptionCount;
    }

    private String getFlockId(String sessionId) {
        String flockId = null;
        if (sessionId != null) {
            flockId = getCustomerAccessService(sessionId);
        }
        return flockId;
    }


    /**
     * 根据 sessionId 查询对应的 YxcscCustomerAccessServiceEntity的FlockId
     */
    private String getCustomerAccessService(String sessionId) {
        LambdaQueryWrapper<YxcscClientFiledServiceEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(YxcscClientFiledServiceEntity::getId, sessionId);
        YxcscClientFiledServiceEntity clientFiledServiceEntity = clientFiledServiceMapper.selectOne(queryWrapper);
        if (clientFiledServiceEntity != null) {
            String currentAccessId = clientFiledServiceEntity.getCurrentAccessId();
            LambdaQueryWrapper<YxcscCustomerAccessServiceEntity> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(YxcscCustomerAccessServiceEntity::getId, currentAccessId);
            YxcscCustomerAccessServiceEntity entity = customerAccessServiceMapper.selectOne(wrapper);
            if (entity != null && entity.getFlockId() != null) {
                return entity.getFlockId();
            }
        }
        return null;
    }


    /**
     * 根据 coustId = userId 获取 flockName
     */
    private String getFlockNameByUserId(Long coustId) {
        if (coustId != null) {
            YxCsUserEntity yxCsUserEntity = userMapper.selectById(coustId);
            if (yxCsUserEntity != null) {
                List<String> stringList = userMapper.getUserFlockNames(coustId);
                if (!stringList.isEmpty()) {
                    return String.join(",", stringList);
                }
            }
        }
        return null;
    }

}
